package org.komarichin.jdo.dao;

import org.komarichin.beans.INews;
import org.komarichin.beans.dao.INewsDAO;
import org.komarichin.jdo.persistence.News;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * User: Michael Komarichin
 * Date: 14.10.2009
 * Time: 10:58:17
 */
@Transactional(readOnly = true)
public class NewsDAO extends JdoGenericLanguageDAOSupport<News, Long> implements INewsDAO<News, Long> {

    private static final long serialVersionUID = 5787747298357259475L;

    private static final Logger log = LoggerFactory.getLogger(NewsDAO.class);

    protected NewsDAO(Class<News> type) {
        super(type);
    }

    @Override
    public News newInstance() {
        return new News();
    }

    @Override
    @Transactional(readOnly = false)
    public News save(News entity) {
        entity.setCreate(new Date());
        entity.setUpdate();
        return super.save(entity);
    }

    @Override
    @Transactional(readOnly = false)
    public Long saveOrUpdate(News news) {
        log.info("save Or Update entity: {}", news);
        News n = getJdoTemplate().getObjectById(News.class, news.getId());
        if (n == null) {
            return save(news).getId();
        } else {
            n.setContent(news.getContent());
            n.setDescription(news.getDescription());
            n.setName(news.getName());
            n.setSource(news.getSource());
            n.setKeyWords(news.getKeyWords());
            n.setTitle(news.getTitle());
            n.setComments(((INews<Long>) news).getComments());
            n.setLanguage(news.getLanguage());
            n.setUpdate();
            return n.getId();
        }
    }


}
